package com.webserver.servlet;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;
import com.webserver.vo.User;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;

public class ShowAllArticleServlet {
    public void service(HttpRequest request, HttpResponse response) {
        System.out.println("开始...");
        List<User> list = new ArrayList<>();
        File dir = new File(".");//项目目录
        if (dir.isDirectory()) {
            File[] subs = dir.listFiles(
                    //lambda创建文件过滤器,条件:名字以.user结尾的子项
                    (f) -> f.getName().endsWith(".article")
            );
            for (File file : subs) {
                try (
                        ObjectInputStream ois = new ObjectInputStream(
                                new FileInputStream(file)
                        )
                ) {
                    User user = (User) ois.readObject();
                    list.add(user);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //设置响应头Content-Type用来告诉浏览器我们拼的是个页面
        response.setContentType("text/html");
        PrintWriter pw = response.getWriter();
        pw.println("<!DOCTYPE html>");
        pw.println("<html lang=\"en\">");
        pw.println("<head>");
        pw.println("<meta charset=\"UTF-8\">");
        pw.println("<title>文章列表</title>");
        pw.println("</head>");
        pw.println("<body>");
        pw.println("<center>");
        pw.println("<h1>文章列表</h1>");
        pw.println("<table border=\"1\">");
        pw.println("<tr><td align=\"center\">标题</td><td align=\"center\">作者</td></tr>");
        //循环userList中的每个用户，来生成对应行
        for (User article : list) {
            pw.println("<tr>");
            pw.println("    <td align=\"center\">" + article.getTitle() + "</td>");
            pw.println("    <td align=\"center\">" + article.getUser() + "</td>");
            pw.println("</tr>");
        }
        pw.println("</table>");
        pw.println("</center>");
        pw.println("</body>");
        pw.println("</html>");
        System.out.println("结束");
    }
}